package com.yupi.referral.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yupi.referral.common.ErrorCode;
import com.yupi.referral.exception.BusinessException;
import com.yupi.referral.mapper.ReferralAnswerMapper;
import com.yupi.referral.model.entity.Referral;
import com.yupi.referral.model.entity.ReferralAnswer;
import com.yupi.referral.model.entity.User;
import com.yupi.referral.service.FileService;
import com.yupi.referral.service.ReferralAnswerService;
import com.yupi.referral.service.ReferralService;
import com.zretc.security.entity.LoginUser;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.List;

/**
* @author ZRETC
* @description 针对表【referral_answer(内推响应)】的数据库操作Service实现
* @createDate 2024-07-04 14:14:28
*/
@Service
public class ReferralAnswerServiceImpl extends ServiceImpl<ReferralAnswerMapper, ReferralAnswer>
    implements ReferralAnswerService{

    @Resource
    private ReferralService referralService;

    @Autowired
    private FileService service;

    private final ReferralAnswerMapper referralAnswerMapper;

    @Autowired
    public ReferralAnswerServiceImpl(ReferralAnswerMapper referralAnswerMapper) {
        this.referralAnswerMapper = referralAnswerMapper;
    }

    /**
     * 响应内推
     *
     * @param referralId
     * @param loginUser
     * @return
     */
    @Override
    public long doReferralAnswer(long referralId, LoginUser loginUser, MultipartFile file) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        // 判断实体是否存在，根据类别获取实体
        Referral referral = referralService.getById(referralId);
        if (referral == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 是否已响应内推
        int userId = loginUser.getUser().getUserId();
        // 每个用户串行响应内推
        ReferralAnswer referralAnswer = new ReferralAnswer();
        referralAnswer.setUserId(userId);
        referralAnswer.setReferralId(referralId);
        String url = service.uploadFile(file);
        referralAnswer.setAddress(url);
        boolean save = this.save(referralAnswer);
        if(!save){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"提交失败");
        }
        return referralAnswer.getId();
    }

    /**
     * 根据referralId返回对应的所有address
     *
     * @param referralId
     * @return
     */
    @Override
    public List<String> getAddressListByReferralId(Long referralId) {

        return referralAnswerMapper.getAddressListByReferralId(referralId);
    }

}




